# Require gems
require 'rubygems'
require 'sinatra/lib/sinatra.rb'
require 'erb'

# Load environment, libs, models, helpers
[
  'lib/*.rb', 
  'environments.rb',
  'models/*.rb', 
  'helpers.rb'
].each do |src_files| 
  Dir.glob(src_files).each { |f| require f }
end

# FILTERS
before do
  consider_request
  path_from_params
end

# INDEX: Navigate directories from comics root dir.
get '/' do
  @dirs = [{:path => @path}.merge!(Archive.find_all_in(@path))]
  if @path.blank?
    @saved = get_place
    erb(:listings, :layout => :full_listings)
  else
    erb :listings
  end
end

# COMIC: Show the table of contents for a particular comic.
get '/comic' do
  @filenames = @archive.short_filenames
  @page = @archive.page(0)

  if !params[:layout]
    erb(:listings)
  else
    @dirs = @archive.path_dirs.collect do |d| 
      {:path => d}.merge(Archive.find_all_in(d))
    end
    erb(:listings, :layout => :full_listings)
  end
end

# READ: Open the comic to a particular page.
get '/read' do
  @pagenum = params[:pagenum].to_i
  erb :read
end

# TURN: ajax-load the next or previous page.
get '/turn' do
  @pagenum = params[:pagenum].to_i
  @page = @archive.page(@pagenum)
  if @page.found?
    save_place(@path, @pagenum)
    header 'Content-Type' => 'application/x-javascript'
    erb %Q`
      {
        "src": "#{escape_javascript(@page.public_filename)}",
        "pagenum": "#{@pagenum}"
      }
    `
  else
    render_404
  end
end
